import { NextResponse } from "next/server";
import connect from "@/utils/mongodb";
import Post from "@/model/Post";
import { writeFile } from "fs/promises";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import fs from "fs";
// 新增：引入认证相关工具（根据你的next-auth配置调整）
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route"; // 你的auth配置路径

const __dirname = dirname(fileURLToPath(import.meta.url));

// 图片URL验证函数（保持不变）
const isValidImageUrl = (url) => {
  if (!url) return false;
  const urlRegex = /^https?:\/\/.+/i;
  const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|webp|svg|ico)$/i;
  return urlRegex.test(url) && imageExtensions.test(url);
};

// 发送一篇文章（保持不变）
export const POST = async (request) => {
  try {
    await connect();
    const contentType = request.headers.get("content-type");
    let postData = {};

    if (contentType?.includes("multipart/form-data")) {
      const formData = await request.formData();

      postData.title = formData.get("title");
      postData.desc = formData.get("desc");
      postData.content = formData.get("content");
      postData.username = formData.get("username"); // 关键：存储发布者用户名

      const imageFile = formData.get("image");
      if (imageFile && imageFile.name) {
        const filename = `${Date.now()}-${imageFile.name.replace(/\s+/g, "-")}`;
        const imagePath = join(__dirname, "../../../../public/uploads", filename);
        await fs.promises.mkdir(dirname(imagePath), { recursive: true });
        const buffer = Buffer.from(await imageFile.arrayBuffer());
        await writeFile(imagePath, buffer);
        postData.img = `/uploads/${filename}`;
      } else {
        const imgUrl = formData.get("imgUrl") || "";
        if (imgUrl && !isValidImageUrl(imgUrl)) {
          return NextResponse.json(
            { message: "图片URL格式无效，请使用http/https开头的图片链接（支持jpg、png等格式）" },
            { status: 400 }
          );
        }
        postData.img = imgUrl;
      }
    } else {
      const jsonData = await request.json();
      postData = jsonData;

      if (postData.img && !isValidImageUrl(postData.img)) {
        return NextResponse.json(
          { message: "图片URL格式无效，请使用http/https开头的图片链接（支持jpg、png等格式）" },
          { status: 400 }
        );
      }
    }

    if (!postData.title || !postData.desc || !postData.content) {
      return NextResponse.json(
        { message: "标题、简介和内容为必填项" },
        { status: 400 }
      );
    }

    const newPost = new Post(postData);
    await newPost.save();
    return NextResponse.json(newPost, { status: 201 });

  } catch (error) {
    console.error("发布文章错误:", error);
    return NextResponse.json(
      { message: "发布文章失败" },
      { status: 500 }
    );
  }
};

// 重点修复：获取文章列表（实现账户隔离）
export const GET = async (request) => {
  try {
    // 1. 验证用户登录状态
    const session = await getServerSession(authOptions);
    if (!session || !session.user) {
      return NextResponse.json(
        { message: "未授权访问，请先登录" },
        { status: 401 }
      );
    }

    // 2. 获取当前登录用户的用户名（与发布时存储的username对应）
    const currentUser = session.user.name; // 确保与POST中的username字段一致

    // 3. 连接数据库，只查询当前用户的文章
    await connect();
    const userPosts = await Post.find({ username: currentUser }); // 核心：按username过滤

    return NextResponse.json(userPosts); // 返回当前用户的文章列表

  } catch (error) {
    console.error("获取文章失败:", error);
    return NextResponse.json(
      { message: "获取文章失败" },
      { status: 500 }
    );
  }
};

// 删除文章（补充权限验证）
export const DELETE = async (request) => {
  try {
    // 1. 验证用户登录
    const session = await getServerSession(authOptions);
    if (!session || !session.user) {
      return NextResponse.json(
        { message: "未授权访问，请先登录" },
        { status: 401 }
      );
    }

    // 2. 获取要删除的文章ID
    const id = request.nextUrl.searchParams.get("id");
    if (!id) {
      return NextResponse.json(
        { message: "缺少文章ID" },
        { status: 400 }
      );
    }

    // 3. 验证文章所有权（确保用户只能删除自己的文章）
    await connect();
    const post = await Post.findById(id);
    if (!post) {
      return NextResponse.json(
        { message: "文章不存在" },
        { status: 404 }
      );
    }

    // 4. 检查当前用户是否为文章发布者
    if (post.username !== session.user.name) {
      return NextResponse.json(
        { message: "无权删除他人的文章" },
        { status: 403 }
      );
    }

    // 5. 执行删除
    await Post.findByIdAndDelete(id);
    return NextResponse.json({ message: "文章已删除" }, { status: 200 });

  } catch (error) {
    console.error("删除文章失败:", error);
    return NextResponse.json(
      { message: "删除文章失败" },
      { status: 500 }
    );
  }
};